package cn.ddiancan.dm.mulidatasource.context;

import org.springframework.util.CollectionUtils;

import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;

/**
 * datasource
 *
 * @author Amos
 * @since 2024-08-19
 */
public class DataSourceContextHolder {
    private static final ThreadLocal<String> contextHolder = new ThreadLocal<>();
    private static final ThreadLocal<List<Connection>> connectionHolder = new ThreadLocal<>();

    /**
     * 获取指定数据库路由key
     *
     * @return
     */
    public static String getDataSourceKey() {
        return contextHolder.get();
    }

    public static void setDataSourceKey(String dataSourceKey) {
        contextHolder.set(dataSourceKey);
    }

    public static void clearDataSourceKey() {
        contextHolder.remove();
    }

    /**
     * 获取指定数据库路由key
     *
     * @return
     */
    public static List<Connection> getConnectionHolder() {
        return connectionHolder.get();
    }

    public static void setConnectionHolder(Connection connection) {
        if (CollectionUtils.isEmpty(connectionHolder.get())) {
            connectionHolder.set(new ArrayList<>());
        }
        connectionHolder.get().add(connection);
    }

    public static void clearConnectionHolder() {
        connectionHolder.remove();
    }
}
